package com.ruoyi.wechattokenutils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@RestController
@RequestMapping("/token")
public class WeChatUtilController extends HttpServlet {
    private String signature;
    private String timestamp;
    private String nonce;
    private String echostr;
    @GetMapping("/get")
    public String doGet(){
        System.out.println("========================");
        return "测试微信";
    }

    /**
     * 验证微信消息
     *
     * @param request
     * @return
     */
    @GetMapping("/check")
    public String checkWxMsg(HttpServletRequest request) {
        Logger logger= LoggerFactory.getLogger(WeChatUtilController.class);
        /**
         * 微信加密签名
         */
        String signature = request.getParameter("signature");
        /**
         * 随机字符串
         */
        String echostr = request.getParameter("echostr");
        /**
         * 时间戳
         */
        String timestamp = request.getParameter("timestamp");
        /**
         * 随机数
         */
        String nonce = request.getParameter("nonce");

        String[] str={timestamp,nonce,WxConstants.TOKEN};
        //将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(str);
        StringBuffer sb = new StringBuffer();
        //将三个参数字符串拼接成一个字符串进行sha1加密
        for (String param:str) {
            sb.append(param);
        }
        //获取到加密过后的字符串
        String encryptStr = EncryptionUtil.encrypt("SHA1", sb.toString());
        //判断加密后的字符串是否与微信的签名一致
        if(signature.equalsIgnoreCase(encryptStr)){
            return echostr;
        }
        logger.error("这不是微信发来的消息！！");
        return "失败！！！";
    }


}
